from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import logging
import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core import settings, setup_logging, get_logger, lifespan
from app.core.exception_handlers import add_exception_handlers
from app.routers import note_folder, note_subject, note_content, home, search, setting

# 配置日志
setup_logging()
logger = get_logger(__name__)

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.app_name,
    description="一个基于FastAPI + PostgreSQL的现代化笔记管理系统后端服务",
    version="1.0",
    debug=settings.debug,
    lifespan=lifespan,
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该指定具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加异常处理器
add_exception_handlers(app)

# 注册路由
app.include_router(note_folder)
app.include_router(note_subject)
app.include_router(note_content)
app.include_router(home)
app.include_router(search)
app.include_router(setting)


@app.get("/")
async def read_root():
    """
    根路径接口
    返回应用基本信息
    """
    logger.info("访问根路径接口")
    return {
        "message": "欢迎使用词仙笔记后端服务",
        "app_name": settings.app_name,
        "version": "1.0.0",
        "status": "running",
    }


@app.get("/health")
async def health_check():
    """
    健康检查接口
    """
    return {"status": "healthy", "app_name": settings.app_name, "version": "1.0.0"}
